//
//  UIView+Theme.m
//  夜间模式demo
//
//  Created by aaaa on 2020/5/28.
//  Copyright © 2020 aaaa. All rights reserved.

#import <Foundation/Foundation.h>
#import "UIView+Theme.h"
#import "UIColor+Theme.h"
#import "BCSkinTool.h"
#import "BCThemeDefine.h"
#import <Objc/runtime.h>

static NSString *const BCTheme_backGroundColorKey = @"BCTheme_backGroundColorKey";


@interface UIView(Theme)


@end
@implementation UIView

+(void)load {    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        exchangeInstanceMethod(@selector(setBackgroundColor:), @selector(bc_setBackgroudColor:), [self class], [self class]);
        exchangeInstanceMethod(@selector(didMoveToSuperview), @selector(bc_didMoveToSuperView), [self class], [self class]);
        exchangeInstanceMethod(@selector(backgroundColor), @selector(bc_backgroundColor), [self class], [self class]);
    });
}

-(void)dealloc{
    [[BCSkinTool shareInstance]removeThemeObserveView:self];
}

-(void)bc_setBackgroudColor:(UIColor *)color{
    objc_setAssociatedObject(self, &BCTheme_backGroundColorKey, color, OBJC_ASSOCIATION_RETAIN);
    [self bc_setBackgroudColor:color];
}

//backgrond比较特殊 没办法重写它的get方法。并且它是copy类型，每次拿到的都是一个新的值。
-(UIColor *)bc_backgroundColor {
    UIColor *color = objc_getAssociatedObject(self,&BCTheme_backGroundColorKey);
    NSLog(@"color.name = %@",color.name);
    return color;
}

-(void)bc_didMoveToSuperView {
    [self bc_didMoveToSuperView];
    
//    if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
//        NSLog(@"button label frame = %@",NSStringFromCGRect(self.frame));
//        NSLog(@"- value = %@",[self performSelector:NSSelectorFromString(@"textColor")]);
//        NSLog(@"- value = %@",[self performSelector:NSSelectorFromString(@"text")]);
//    }
    if (self.superview == nil) {//remove
        [[BCSkinTool shareInstance]removeThemeObserveView:self];
    } else { //added
        [[BCSkinTool shareInstance]addThemeObserveView:self];
    }
}



@end

